package com.weed.core;


import com.weed.common.Constants;
import com.weed.common.Log;
import com.weed.common.ObjectFactory;
import com.weed.helper.InvokerHelper;
import com.weed.helper.ArgumentHolder;
import com.weed.helper.ClassHelper;
import com.weed.helper.LogFactory;

/**
 * /**
  * 函数说明：
  *    业务逻辑封装(数据存储、事务处理).
  * @param commonInput 用于获得所有的输入参数。
  * @param DAO 数据访问组件。
  *
  * @return CommonOutput 用于获得所有的输出。
  * @throws com.weed.core.WeedException
  * 方法名称可以自定义，参数必须一样。
  *
  * sample:
  *    public CommonOutput addUser(CommonInput commonInput,DataProcess process) throws WeedException;</p>
  *    public CommonOutput deleteUser(CommonInput commonInput,DataProcess process) throws WeedException;</p>
  *
  * @author Jason Zhuo
  * @version 1.0
  */

public abstract class Action {

  /**
   * 用于记录日志。
   */
  public Log log;
  /**
   * 统一的命令执行接口，进行命令调转，支持流程控制。
   * @param commonInput CommonInput
   * @param process DataProcess
   * @return CommonOutput
   * @throws WeedException
   */
  public CommonOutput _execute_action(CommonInput commonInput,
                                      DataProcess process) {
    //输出。
    CommonOutput commonOutput= null;
    DataProcess dataProcess = null;
    try {
       commonOutput = (CommonOutput) ObjectFactory.getObject(com.weed.common.Environment.DEFAULT_COMMONOUTPUT_IMPL);
      //逻辑包名。格式：com.weed.system.User等
      String logic_package = (String) commonInput.get(Constants.DATA_BEAN);
      //逻辑对象 User.addUser(this);
      String operation_action_command = (String) commonInput.get(Constants.
          OPERATION_LOGIC_COMMAND);
      //做为Action的日志记录
      //确认逻辑包是否存在。
      if (logic_package == null || logic_package.trim().length() == 0) {
        commonOutput.setRetCode( -1);
        commonOutput.setRetDesc("对不起，对应的业务逻辑处理对象不存在。[" + logic_package + "]");
        return commonOutput;
      }
      //对象不为空，为空将进入异常处理。
      Object obj = ClassHelper.newInstance(logic_package);
      int index = operation_action_command.indexOf(".");
      int length = operation_action_command.indexOf("(");
      ((Action)obj).log = LogFactory.getLog(obj.getClass());
      if (index < 0) {
        commonOutput.setRetCode( -1);
        commonOutput.setRetDesc("方法没有指定!");
      }
      String method = "";
      if(length >0)
         method = operation_action_command.substring(index + 1, length);
      else
         method = operation_action_command.substring(index + 1);
      ArgumentHolder params = new ArgumentHolder();
      params.setArgument(0,commonInput,CommonInput.class);
      params.setArgument(1,dataProcess,DataProcess.class);
      if (InvokerHelper.isMethod(obj, method,params)) {
        commonOutput = (CommonOutput) InvokerHelper.call(obj, method,params);
      }
    }
    catch (Exception ex) {
      commonOutput.setRetCode(-1);
      commonOutput.setRetDesc("业务逻辑调度时发生异常!");
      commonOutput.setException(new WeedException(ex));
      return commonOutput;
    }
    return commonOutput;
  }
}
